package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.Collections;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.service.CollectionsService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 收藏接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/collections")
@Slf4j
public class CollectionsController {

    @Resource
    private CollectionsService collectionsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 添加收藏
     *
     * @param collections
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCollection(@RequestBody Collections collections, HttpServletRequest request) {
        if (collections == null || collections.getTarget_id() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        collections.setUser_id(loginUser.getId());
        
        // 检查是否已经收藏过该文章
        Collections existingCollection = collectionsService.lambdaQuery()
                .eq(Collections::getUser_id, loginUser.getId())
                .eq(Collections::getTarget_id, collections.getTarget_id())
                .one();
        if (existingCollection != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "已收藏过该目标");
        }
        
        boolean result = collectionsService.save(collections);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCollectionId = collections.getId();
        return ResultUtils.success(newCollectionId);
    }

    /**
     * 取消收藏
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCollection(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Collections oldCollection = collectionsService.getById(id);
        ThrowUtils.throwIf(oldCollection == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldCollection.getUser_id().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = collectionsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 根据文章ID取消收藏
     *
     * @param articleId
     * @param request
     * @return
     */
    @PostMapping("/delete/by-article")
    public BaseResponse<Boolean> deleteCollectionByArticleId(@RequestParam Long articleId, HttpServletRequest request) {
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        
        boolean result = collectionsService.lambdaUpdate()
                .eq(Collections::getUser_id, loginUser.getId())
                .eq(Collections::getTarget_id, articleId)
                .remove();
        return ResultUtils.success(result);
    }

    /**
     * 更新收藏（移动到其他收藏夹）
     *
     * @param collections
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateCollection(@RequestBody Collections collections, HttpServletRequest request) {
        if (collections == null || collections.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        // 判断是否存在
        Collections oldCollection = collectionsService.getById(collections.getId());
        ThrowUtils.throwIf(oldCollection == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldCollection.getUser_id().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = collectionsService.updateById(collections);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取收藏
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Collections> getCollectionById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Collections collection = collectionsService.getById(id);
        if (collection == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(collection);
    }

    /**
     * 分页获取当前用户的收藏列表
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/my")
    public BaseResponse<Page<Collections>> listMyCollections(
            @RequestParam long current, 
            @RequestParam long size,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Page<Collections> collectionPage = collectionsService.lambdaQuery()
                .eq(Collections::getUser_id, loginUser.getId())
                .orderByDesc(Collections::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(collectionPage);
    }

    /**
     * 根据收藏夹ID获取收藏列表
     *
     * @param folderId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-folder")
    public BaseResponse<Page<Collections>> getCollectionsByFolderId(
            @RequestParam Long folderId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            HttpServletRequest request) {
        if (folderId == null || folderId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        Page<Collections> collectionPage = collectionsService.lambdaQuery()
                .eq(Collections::getFolder_id, folderId)
                .orderByDesc(Collections::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(collectionPage);
    }

    /**
     * 根据文章ID获取收藏列表
     *
     * @param articleId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-article")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Collections>> getCollectionsByArticleId(
            @RequestParam Long articleId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        Page<Collections> collectionPage = collectionsService.lambdaQuery()
                .eq(Collections::getTarget_id, articleId)
                .orderByDesc(Collections::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(collectionPage);
    }

    /**
     * 分页获取收藏列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Collections>> listCollectionByPage(@RequestParam long current, @RequestParam long size) {
        Page<Collections> collectionPage = collectionsService.page(new Page<>(current, size));
        return ResultUtils.success(collectionPage);
    }

    /**
     * 检查用户是否收藏了某篇文章
     *
     * @param articleId
     * @param request
     * @return
     */
    @GetMapping("/check")
    public BaseResponse<Boolean> checkCollection(@RequestParam Long articleId, HttpServletRequest request) {
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        Collections collection = collectionsService.lambdaQuery()
                .eq(Collections::getUser_id, loginUser.getId())
                .eq(Collections::getTarget_id, articleId)
                .one();
        
        return ResultUtils.success(collection != null);
    }

    /**
     * 获取文章的收藏数量
     *
     * @param articleId
     * @return
     */
    @GetMapping("/count")
    public BaseResponse<Long> getCollectionCount(@RequestParam Long articleId) {
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        long count = collectionsService.lambdaQuery()
                .eq(Collections::getTarget_id, articleId)
                .count();
        
        return ResultUtils.success(count);
    }

    /**
     * 批量删除收藏
     *
     * @param ids
     * @param request
     * @return
     */
    @PostMapping("/batch/delete")
    public BaseResponse<Boolean> batchDeleteCollections(@RequestBody List<Long> ids, HttpServletRequest request) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        
        // 检查所有收藏是否属于当前用户
        List<Collections> collections = collectionsService.listByIds(ids);
        for (Collections collection : collections) {
            if (!collection.getUser_id().equals(loginUser.getId()) && !userService.isAdmin(request)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        
        boolean result = collectionsService.removeByIds(ids);
        return ResultUtils.success(result);
    }

    /**
     * 批量移动收藏到指定收藏夹
     *
     * @param ids
     * @param folderId
     * @param request
     * @return
     */
    @PostMapping("/batch/move")
    public BaseResponse<Boolean> batchMoveCollections(
            @RequestBody List<Long> ids,
            @RequestParam Long folderId,
            HttpServletRequest request) {
        if (ids == null || ids.isEmpty() || folderId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        
        // 检查所有收藏是否属于当前用户
        List<Collections> collections = collectionsService.listByIds(ids);
        for (Collections collection : collections) {
            if (!collection.getUser_id().equals(loginUser.getId()) && !userService.isAdmin(request)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            collection.setFolder_id(folderId);
        }
        
        boolean result = collectionsService.updateBatchById(collections);
        return ResultUtils.success(result);
    }

}